package com.ocean.redisson.service;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @version 1.0
 * @className: ReentrantLockUseService
 * @description: ReentrantLock 使用
 * @author: lxq
 * @date: 2021/7/17
 **/
public class ReentrantLockUseService {
    private final Lock lock = new ReentrantLock();
    private int count;

    private AtomicInteger atomicInteger = new AtomicInteger(0);
    public void add(){
        lock.lock();
        try{
            count++;
            atomicInteger.incrementAndGet();
        }finally {
            lock.unlock();
        }
    }

    public void tryAdd() throws InterruptedException {
        if (lock.tryLock(1, TimeUnit.SECONDS)){
            try {
                count++;
                atomicInteger.incrementAndGet();
            }finally {
                lock.unlock();
            }
        }
    }
}
